// Parts Copyright 2008 Newgrove Consultants Limited
// Modified By John Diss 
// From original work:
//
// Copyright 2006 - Ricardo Stuven (rstuven@gmail.com)
//
// This file is part of MsSqlSpatial.
// MsSqlSpatial is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// 
// MsSqlSpatial is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public License
// along with MsSqlSpatial; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 

using System.Collections.Generic;
using System.Data.SqlTypes;
using GeoAPI.DataStructures;
using GeoAPI.Geometries;
using GisSharpBlog.NetTopologySuite.Operation.Polygonize;
using Microsoft.SqlServer.Server;
using MsSqlSpatial;
using MsSqlCoordinate2D = NetTopologySuite.Coordinates.BufferedCoordinate;

public partial class UserDefinedFunctions
{
    /// <summary>
    /// Returns a GeometryCollection containing possible polygons 
    /// formed from the constituent linework of a set of geometries.
    /// 
    /// To Do: remove dependency on MsSqlCoordinate if Polygonizer becomes abstract
    /// </summary>
    [SqlFunction(IsDeterministic = true)]
    public static SqlBytes Polygonize(SqlBytes ewkb)
    {
        IGeometry geometry = ConvertGeometry.ToGeometry(ewkb);
        if (geometry != null)
        {
            var polygonizer = new Polygonizer<MsSqlCoordinate2D>();

            if (geometry is IGeometryCollection)
                polygonizer.Add(
                    new List<IGeometry<MsSqlCoordinate2D>>((geometry as IGeometryCollection<MsSqlCoordinate2D>)));
            else
                polygonizer.Add((IGeometry<MsSqlCoordinate2D>) geometry);


            return ConvertGeometry.ToSqlBytes(
                Global
                    .Services[geometry.Srid]
                    .CreateGeometryCollection
                    (Caster.Upcast<IGeometry, IPolygon<MsSqlCoordinate2D>>(polygonizer.Polygons))
                , GeometryUtilities.MsSqlSpatialSrid(geometry));
        }


        return ConvertGeometry.ToSqlBytes(
            Global
                .Services
                .GeometryFactory
                .CreateGeometryCollection());
    }
} ;